package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.controller.CartController;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mysql.cj.Session;
import com.sun.xml.internal.ws.util.CompletedFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ListUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {
    private final String CART_PREFIX = "gulimall:cart:";


    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;


    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //获取到我们的购物车
        // 远程查询上商品的信息

        String o = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(o)) {
            //购物车无商品
            //2. 商品添加到购物车
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.info(skuId);
                SkuInfoVo skuInfoData = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setChecked(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfoData.getSkuDefaultImg());
                cartItem.setTitle(skuInfoData.getSkuTitle());
                cartItem.setPrice(skuInfoData.getPrice());
                cartItem.setSkuid(skuId);
            }, executor);
            //远程查询skuinfo 的 属性组合信息
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);
            CompletableFuture.allOf(getSkuInfoTask, voidCompletableFuture).get();
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);
            return cartItem;
        } else {
            CartItem cartItem = JSON.parseObject(o, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            //更新redis
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }


        //提前转为string 类型的json 字符券, 避免使用自带的检jdk序列化


    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            //临时用户

            BoundHashOperations<String, Object, Object> cartOps = getCartOps();
            String key = cartOps.getKey();
            String o= CART_PREFIX + userInfoTo.getUserKey();
            Object o1 = cartOps.get(key.toString());
            List<CartItem> cartItem = getCartItem(o.toString());
            cart.setItems(cartItem);
        } else {
            // 登录用户 ,  需要合并购物项
            String key = CART_PREFIX + CartInterceptor.threadLocal.get().getUserId();
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);
            List<CartItem> tempCartItems = getCartItem(CART_PREFIX + userInfoTo.getUserKey());
            if (tempCartItems != null) {
                for (CartItem cartItem : tempCartItems) {
                    CartItem cartItem1 = addToCart(cartItem.getSkuid(), cartItem.getCount());
                }
                redisTemplate.delete(CART_PREFIX + userInfoTo.getUserKey());
            }
            //合并后, 去redis 重新获取数据
            List<CartItem> cartItem = getCartItem(key);
            cart.setItems(cartItem);
        }
        return cart;
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        Object o = cartOps.get(skuId.toString());
        CartItem cartItem = getCartItem(skuId);
        cartItem.setChecked(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }


    /**
     * 修改商品数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeCartItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCartItemChecked() {
        Long userId = CartInterceptor.threadLocal.get().getUserId();
        List<CartItem> cartItems = getCartItem(CART_PREFIX + userId);
        List<CartItem> cartItemList= cartItems.stream().filter(item -> {
            boolean checked = item.isChecked();
            return checked;
        }).map(item->{
            //查询当前的商品的最新价格
            BigDecimal lastPrice = productFeignService.getLastPrice(item.getSkuid());
            item.setPrice(lastPrice);
            return item;
        }).collect(Collectors.toList());
        return cartItemList;
    }

    @Override
    public List<CartItem> getCartItemByMemberId() {
        List<Object> values = getCartOps().values();
        List<CartItem> cartItems = JSONArray.parseArray(values.toString(), CartItem.class);
        List<CartItem> cartItemList = cartItems.stream().filter(item -> {
            return item.isChecked();
        }).collect(Collectors.toList());
        return cartItemList;
    }


    /**
     * 获取购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        // 1.
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
        return ops;
    }

    /**
     * 抽取获取购物项
     */
    private List<CartItem> getCartItem(String cartKey) {
        List<Object> values = redisTemplate.boundHashOps(cartKey).values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, new TypeReference<CartItem>() {
                });
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }


}